package cn.cmeizu.spring6.jdbc.tx.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;

/**
 * @author cmeizu
 * @date 2023/2/19 12:20
 */
//配置类
@Configuration
@ComponentScan("cn.cmeizu.spring6.jdbc.tx")
//开启事务管理
@EnableTransactionManagement
public class SpringConfig {

  @Value("${jdbc.username}")
  private String username;
  @Value("${jdbc.password}")
  private String password;
  @Value("${jdbc.url}")
  private String url;
  @Value("${jdbc.driver}")
  private String driver;

  public void setUsername(String username) {
    this.username = username;
  }

  public void setPassword(String password) {
    this.password = password;
  }

  public void setUrl(String url) {
    this.url = url;
  }

  public void setDriver(String driver) {
    this.driver = driver;
  }

  //@Bean
  //public DataSource getDataSource() {
  //  DruidDataSource druidDataSource = new DruidDataSource();
  //  druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
  //  druidDataSource.setUsername("root");
  //  druidDataSource.setPassword("12345678");
  //  druidDataSource.setUrl("jdbc:mysql://localhost:3306/spring?serverTimezone=UTC");
  //  return druidDataSource;
  //}

  @Bean
  public DataSource getDataSource() {
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setDriverClassName(driver);
    druidDataSource.setUsername(username);
    druidDataSource.setPassword(password);
    druidDataSource.setUrl(url);
    return druidDataSource;
  }

  @Bean(name = "jdbcTemplate")
  public JdbcTemplate getJdbcTemplate(DataSource dataSource) {
    JdbcTemplate jdbcTemplate = new JdbcTemplate();
    jdbcTemplate.setDataSource(dataSource);
    return jdbcTemplate;
  }

  @Bean
  public DataSourceTransactionManager dataSourceTransactionManager(DataSource dataSource) {
    return new DataSourceTransactionManager(dataSource);
  }

}
